#include "defectdlg.h"
#include "ui_defectdlg.h"
#include <QCheckBox>
#include <QComboBox>
#include <QGraphicsDropShadowEffect>
#include <QMessageBox>
#include <QTextStream>
#include <ToggleSwitch/toggleswitch.h>


DefectDlg::DefectDlg(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DefectDlg)
{
    ui->setupUi(this);
    this->adjustSize();
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setWindowModality(Qt::ApplicationModal);
    this->setAttribute(Qt::WA_ShowModal,true);
    Qt::WindowFlags flags=Qt::Widget;
    flags |=Qt::WindowMinMaxButtonsHint;
    flags |=Qt::WindowCloseButtonHint;
    this->setWindowFlags(flags);



    QFile dlg_qss(":/qss/dlg.qss");
    if (dlg_qss.open(QFile::ReadOnly))
    {
        QTextStream filetext(&dlg_qss);
        QString stylesheet = filetext.readAll();
        this->setStyleSheet(stylesheet);
        dlg_qss.close();
    }

    m_pMsg = new Message(this);
    m_sql.init("defect_data");

    QGraphicsDropShadowEffect *shadow_effectA = new QGraphicsDropShadowEffect(this);
    QGraphicsDropShadowEffect *shadow_effectB = new QGraphicsDropShadowEffect(this);
    QGraphicsDropShadowEffect *shadow_effectC = new QGraphicsDropShadowEffect(this);
    shadow_effectA->setOffset(0, 0);
    shadow_effectA->setColor(QColor(150,150,150));
    shadow_effectA->setBlurRadius(6);

    shadow_effectB->setOffset(0, 0);
    shadow_effectB->setColor(QColor(150,150,150));
    shadow_effectB->setBlurRadius(6);

    shadow_effectC->setOffset(0, 0);
    shadow_effectC->setColor(QColor(150,150,150));
    shadow_effectC->setBlurRadius(6);


    ui->Info_gBox_1->setGraphicsEffect(shadow_effectA);
    ui->Info_gBox_2->setGraphicsEffect(shadow_effectB);
    ui->tabWidget->setGraphicsEffect(shadow_effectC);

    initTableWidget(ui->tableWidget_1);
    initTableWidget(ui->tableWidget_2);
    initTableWidget(ui->tableWidget_3);
    initTableWidget(ui->tableWidget_4);
    initTableWidget(ui->tableWidget_5);
    initTableWidget(ui->tableWidget_6);

    iniTable1();
    iniTable2();
    iniTable3();
    iniTable4();
    iniTable5();
    iniTable6();

}

DefectDlg::~DefectDlg()
{
    delete ui;
}

void DefectDlg::iniPage(int state)
{
    switch (state) {
    case 1: //add
        ui->labState->setText(tr("state:add"));
        ui->Bt_Print->hide();
        ui->label_4->hide();
        ui->label_5->hide();
        ui->label_chang->hide();
        ui->label_create->hide();
        ui->Bt_Add->hide();
        ui->Bt_Delete->hide();
        ui->Bt_Updata->hide();
        m_nRunState = 1;
        break;
    case 2: // search
        ui->labState->setText(tr("state:search"));
        setWidgetsEnabled(this,false);
        ui->Bt_Save->hide();
        ui->Bt_Add->hide();
        ui->Bt_Delete->hide();
        ui->Bt_Updata->hide();
        m_nRunState = 2;
        break;
    case 3: // change
        ui->labState->setText(tr("state:change"));
        setWidgetsEnabled(this,true);
        ui->Bt_Print->hide();
        ui->Bt_Add->hide();
        ui->Bt_Delete->hide();
        ui->Bt_Save->hide();
        m_nRunState = 3;
        break;
    }
}

void DefectDlg::iniPlanPage(const int& scheme_id)
{
    ui->Info_gBox_1->hide();
    ui->Info_gBox_2->hide();
    iniPage(2);
    if(scheme_id==0)return;
    upPageData(scheme_id);
}

void DefectDlg::upPageData(int id)
{
    if(id==0){
        ui->lineEdit->setText("");
        ui->lineEdit_2->setText("");
        iniTable1();
        iniTable2();
        iniTable3();
        iniTable4();
        iniTable5();
        iniTable6();
        return;
    }
    m_currentSchemeId = id; // 保存当前方案ID
    isInitializationComplete = false;
    DefectScheme scheme;
    // 主缺陷数据填充
    m_sql.queryDefectScheme(id,scheme);
    ui->Edit_defect->setText(scheme.schemeName);
    ui->lineEdit->setText(QString::number(scheme.headEnd));
    ui->lineEdit_2->setText(QString::number(scheme.edgeSize));
    ui->label_create->setText(scheme.createTime);
    ui->label_chang->setText(scheme.changeTime);

    // 表1 数据填充
    upPageTable1(scheme.defectSettings);
    // 表2 数据填充
    // 表3 数据填充
    upPageTable3(scheme.generalParams);
    // 表4 数据填充
    upPageTable4(scheme.qualityGrades);
    // 表5 数据填充
    upPageTable5(scheme.edgeParams);
    // 表6 数据填充
    upPageTable6(scheme.fixedLengths);

    isInitializationComplete = true;
}

void DefectDlg::initTableWidget(QTableWidget *table)
{
    if (!table) return; // 安全校验
    table->setShowGrid(true); // 显示网格线
    table->setSelectionBehavior(QAbstractItemView::SelectRows); // 选中整行
    table->setSelectionMode(QAbstractItemView::SingleSelection); // 单选模式
    // 自动拉伸列宽适应窗口
    table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 隐藏垂直表头（行号）
    table->verticalHeader()->hide();
}

void DefectDlg::iniTable1()
{
    QStringList header;
    header << tr("defect name") << tr("activate") << tr("long edge(mm)")
           << tr("short edge(mm)") << tr("compensation(mm)") << tr("open(mm)")
           << tr("area auxiliary") << tr("unacceptable") << tr("edge correction")
           << tr("command credibility") << tr("sort order");

    ui->tableWidget_1->setColumnCount(header.size());
    ui->tableWidget_1->setHorizontalHeaderLabels(header);
    ui->tableWidget_1->setRowCount(10);

    QList<QString> listDefect = {tr("Defect_DK"), tr("Defect_LK"), tr("Defect_CR"),
                                 tr("Defect_HB"), tr("Defect_EM"),
                                 tr("Defect_WH"), tr("Defect_SM"), tr("Defect_BD"),
                                 tr("Defect_PT"), tr("Defect_RS")};

    for(int i = 0; i < listDefect.size(); i++){

        QTableWidgetItem* textItem = new QTableWidgetItem(listDefect[i]);
        textItem->setTextAlignment(Qt::AlignCenter);
        textItem->setFlags(textItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_1->setItem(i, 0, textItem);


        ToggleSwitch* pSwitch = new ToggleSwitch(ui->tableWidget_1);
        pSwitch->setShowText(false);
        pSwitch->setFixedSize(60, 24);
        QWidget* switchContainer = new QWidget();
        QHBoxLayout* switchLayout = new QHBoxLayout(switchContainer);
        switchLayout->addWidget(pSwitch);
        switchLayout->setAlignment(Qt::AlignCenter);
        switchLayout->setContentsMargins(15, 0, 15, 0);
        ui->tableWidget_1->setCellWidget(i, 1, switchContainer);


        for(int col : {2,3,4,5,8,9}) {
            QTableWidgetItem* item = new QTableWidgetItem("0");
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget_1->setItem(i, col, item);
        }


        auto createCenteredCheckbox = [&](){
            QCheckBox* cb = new QCheckBox();
            QWidget* container = new QWidget();
            QHBoxLayout* layout = new QHBoxLayout(container);
            layout->addWidget(cb, 0, Qt::AlignCenter);
            layout->setContentsMargins(0,0,0,0);
            return container;
        };
        ui->tableWidget_1->setCellWidget(i, 6, createCenteredCheckbox());
        ui->tableWidget_1->setCellWidget(i, 7, createCenteredCheckbox());

        // 添加sort_order列 (自然增长从1开始)
        QTableWidgetItem* sortItem = new QTableWidgetItem(QString::number(i+1));
        sortItem->setTextAlignment(Qt::AlignCenter);
        sortItem->setFlags(sortItem->flags() & ~Qt::ItemIsEditable); // 禁止编辑
        ui->tableWidget_1->setItem(i, 10, sortItem);  // 第11列是sort_order
    }

    // 调整表格尺寸
    ui->tableWidget_1->setMinimumWidth(header.size() * 70 + 200);
    ui->tableWidget_1->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableWidget_1->setColumnHidden(10, true); // 隐藏sort_order列
}

void DefectDlg::iniTable2()
{
    QStringList header;
    header << tr("defect name")<< tr("activate");
    ui->tableWidget_2->setColumnCount(header.size());
    ui->tableWidget_2->setHorizontalHeaderLabels(header);


    ui->tableWidget_2->setRowCount(10);
    QList<QString> listDefect = {tr("Defect_DK"), tr("Defect_LK"), tr("Defect_CR"),
                                 tr("Defect_HB"), tr("Defect_EM") ,
                                 tr("Defect_WH"), tr("Defect_SM"), tr("Defect_BD"),
                                 tr("Defect_PT"), tr("Defect_RS")};
    for(int i=0; i<10; i++){
        // 1. 文本列 (居中)
        QTableWidgetItem* textItem = new QTableWidgetItem(listDefect[i]);
        textItem->setTextAlignment(Qt::AlignCenter);
        textItem->setFlags(textItem->flags() & ~Qt::ItemIsEditable); // 禁止编辑
        ui->tableWidget_2->setItem(i, 0, textItem);

        // 2. ToggleSwitch (居中+边距)
        ToggleSwitch* pSwitch = new ToggleSwitch(ui->tableWidget_2);
        pSwitch->setShowText(false);
        pSwitch->setFixedSize(60, 24);

        QWidget* switchContainer = new QWidget();
        QHBoxLayout* switchLayout = new QHBoxLayout(switchContainer);
        switchLayout->addWidget(pSwitch);
        switchLayout->setAlignment(Qt::AlignCenter);
        switchLayout->setContentsMargins(15, 0, 15, 0); // 左右边距

        ui->tableWidget_2->setCellWidget(i, 1, switchContainer);
    }
}

void DefectDlg::iniTable3()
{
    QStringList header;
    header << tr("parm name") << tr("parm value(mm)") << tr("sort order");
    ui->tableWidget_3->setColumnCount(header.size());
    ui->tableWidget_3->setHorizontalHeaderLabels(header);
    ui->tableWidget_3->setRowCount(16);

    QList<QString> listDefect = {tr("General_minDist"),
                                 tr("General_fluorescence"),
                                 tr("General_NMS"),
                                 tr("General_shortAngle"),
                                 tr("General_shortEdge"),
                                 tr("General_missingAngle"),
                                 tr("General_minWoodLen"),
                                 tr("General_maxWoodLen"),
                                 tr("General_maxWaste"),
                                 tr("General_optWoodLen"),
                                 tr("General_truncation"),
                                 tr("General_removeTailing"),
                                 tr("General_sawThickness"),
                                 tr("General_defectMode"),
                                 tr("General_maxDowngrade"),
                                 tr("General_walnut")};

    for(int i = 0; i < listDefect.size(); i++){

        QTableWidgetItem* textItem = new QTableWidgetItem(listDefect[i]);
        textItem->setTextAlignment(Qt::AlignCenter);
        textItem->setFlags(textItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_3->setItem(i, 0, textItem);

        // 添加sort_order列 (自然增长从1开始)
        QTableWidgetItem* sortItem = new QTableWidgetItem(QString::number(i+1));
        sortItem->setTextAlignment(Qt::AlignCenter);
        sortItem->setFlags(sortItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_3->setItem(i, 2, sortItem);  // 第3列是sort_order
    }


    for(int col : {0,2,4,5,6,7,8,9,10,11,12,13,14}) {
        QTableWidgetItem* item = new QTableWidgetItem("0");
        item->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_3->setItem(col, 1, item);
    }


    auto createToggleSwitch = [&](){
        ToggleSwitch* pSwitch = new ToggleSwitch(ui->tableWidget_3);
        pSwitch->setShowText(false);
        pSwitch->setFixedSize(60, 24);
        QWidget* container = new QWidget();
        QHBoxLayout* layout = new QHBoxLayout(container);
        layout->addWidget(pSwitch);
        layout->setAlignment(Qt::AlignCenter);
        layout->setContentsMargins(15, 0, 15, 0);
        return container;
    };

    ui->tableWidget_3->setCellWidget(1, 1, createToggleSwitch());
    ui->tableWidget_3->setCellWidget(3, 1, createToggleSwitch());
    ui->tableWidget_3->setCellWidget(15, 1, createToggleSwitch());

    // 调整列宽
    ui->tableWidget_3->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableWidget_3->setColumnHidden(2, true); // 隐藏sort_order列
}

void DefectDlg::iniTable4()
{
    QStringList header;
    header << tr("Quality Level") << tr("Value Weight") << tr("sort order");
    ui->tableWidget_4->setColumnCount(header.size());
    ui->tableWidget_4->setHorizontalHeaderLabels(header);
    ui->tableWidget_4->setRowCount(3);

    QList<QString> listDefect = {tr("A"), tr("B"), tr("C")};

    for(int i = 0; i < 3; i++){
        QTableWidgetItem* textItem = new QTableWidgetItem(listDefect[i]);
        textItem->setTextAlignment(Qt::AlignCenter);
        textItem->setFlags(textItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_4->setItem(i, 0, textItem);

        QTableWidgetItem* sortItem = new QTableWidgetItem(QString::number(i+1));
        sortItem->setTextAlignment(Qt::AlignCenter);
        sortItem->setFlags(sortItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_4->setItem(i, 2, sortItem);
    }

    ui->tableWidget_4->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    ui->tableWidget_4->setColumnHidden(2, true); // 隐藏sort_order列
}

void DefectDlg::iniTable5()
{
    QStringList header;
    header << tr("parm name") << tr("parm value(mm)") << tr("sort order");  // 增加sort_order列
    ui->tableWidget_5->setColumnCount(header.size());
    ui->tableWidget_5->setHorizontalHeaderLabels(header);
    ui->tableWidget_5->setRowCount(3);

    QList<QString> listDefect = {tr("Edge_IgnoreMode"),
                                 tr("Edge_DoubleStepMaxLength"),
                                 tr("Edge_DoubleStepMinLength")};

    for(int i = 0; i < 3; i++){
        QTableWidgetItem* textItem = new QTableWidgetItem(listDefect[i]);
        textItem->setTextAlignment(Qt::AlignCenter);
        textItem->setFlags(textItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_5->setItem(i, 0, textItem);

        QTableWidgetItem* sortItem = new QTableWidgetItem(QString::number(i+1));
        sortItem->setTextAlignment(Qt::AlignCenter);
        sortItem->setFlags(sortItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_5->setItem(i, 2, sortItem);
    }

    ui->tableWidget_5->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    ui->tableWidget_5->setColumnHidden(2, true);  // 隐藏sort_order列
}

void DefectDlg::iniTable6()
{
    QStringList header;
    header << tr("F") << tr("Activation") << tr("Length(mm)") << tr("sort order");  // 增加sort_order列
    ui->tableWidget_6->setColumnCount(header.size());
    ui->tableWidget_6->setHorizontalHeaderLabels(header);
    ui->tableWidget_6->setRowCount(20);

    for(int i = 0; i < 20; i++){
        QString base = tr("FixedSize_");
        QString info = base + QString("%1").arg(i+1, 2, 10, QChar('0'));

        // 名称列
        QTableWidgetItem* textItem = new QTableWidgetItem(info);
        textItem->setTextAlignment(Qt::AlignCenter);
        textItem->setFlags(textItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_6->setItem(i, 0, textItem);

        // ToggleSwitch列
        ToggleSwitch* pSwitch = new ToggleSwitch(ui->tableWidget_6);
        pSwitch->setShowText(false);
        pSwitch->setFixedSize(60, 24);
        QWidget* switchContainer = new QWidget();
        QHBoxLayout* switchLayout = new QHBoxLayout(switchContainer);
        switchLayout->addWidget(pSwitch);
        switchLayout->setAlignment(Qt::AlignCenter);
        switchLayout->setContentsMargins(15, 0, 15, 0);
        ui->tableWidget_6->setCellWidget(i, 1, switchContainer);

        // 长度值列
        QTableWidgetItem* item = new QTableWidgetItem("0");
        item->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_6->setItem(i, 2, item);

        // sort_order列
        QTableWidgetItem* sortItem = new QTableWidgetItem(QString::number(i+1));
        sortItem->setTextAlignment(Qt::AlignCenter);
        sortItem->setFlags(sortItem->flags() & ~Qt::ItemIsEditable);
        ui->tableWidget_6->setItem(i, 3, sortItem);
    }

    ui->tableWidget_6->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
    ui->tableWidget_6->setColumnHidden(3, true);  // 隐藏sort_order列
}

void DefectDlg::upPageTable1(const QList<DefectSetting> &defectSettings)
{
    // 确保数据与表格行数匹配
    int rowCount = ui->tableWidget_1->rowCount();
    int dataCount = defectSettings.size();
    int loopCount = qMin(rowCount, dataCount);

    for (int i = 0; i < loopCount; ++i) {
        const DefectSetting& setting = defectSettings[i];

        //更新缺陷名称 (第0列)
        QTableWidgetItem* nameItem = ui->tableWidget_1->item(i, 0);
        if (nameItem) {
            nameItem->setText(setting.defectName);
        }

        //更新激活状态 (第1列，ToggleSwitch)
        QWidget* switchWidget = ui->tableWidget_1->cellWidget(i, 1);
        if (switchWidget) {
            ToggleSwitch* toggle = switchWidget->findChild<ToggleSwitch*>();
            if (toggle) {
                toggle->setChecked(setting.isActive);
            }
        }

        //更新数值型数据 (第2-5,8-9列)
        auto updateNumericItem = [&](int col, double value) {
            QTableWidgetItem* item = ui->tableWidget_1->item(i, col);
            if (item) {
                item->setText(value > 0 ? QString::number(value) : "0");
            }
        };

        updateNumericItem(2, setting.longEdge);       // 长边尺寸
        updateNumericItem(3, setting.shortEdge);       // 短边尺寸
        updateNumericItem(4, setting.compensation);    // 补偿值
        updateNumericItem(5, setting.openTogether ? 1 : 0); // 共同开启（显示为1/0）
        updateNumericItem(8, setting.edgeCorrection);  // 边缘修正值
        updateNumericItem(9, setting.confidence);     // 置信度

        //更新复选框数据 (第6-7列)
        auto updateCheckbox = [&](int col, bool checked) {
            QWidget* widget = ui->tableWidget_1->cellWidget(i, col);
            if (widget) {
                QCheckBox* cb = widget->findChild<QCheckBox*>();
                if (cb) {
                    cb->setChecked(checked);
                }
            }
        };

        updateCheckbox(6, setting.areaAssist);        // 区域辅助
        updateCheckbox(7, setting.unacceptable);      // 是否不可接受
    }

    // 如果数据少于行数，清空剩余行
    for (int i = dataCount; i < rowCount; ++i) {
        // 清空文本列
        for (int col : {0, 2, 3, 4, 5, 8, 9}) {
            QTableWidgetItem* item = ui->tableWidget_1->item(i, col);
            if (item) {
                item->setText("0");
            }
        }

        // 重置ToggleSwitch
        QWidget* switchWidget = ui->tableWidget_1->cellWidget(i, 1);
        if (switchWidget) {
            ToggleSwitch* toggle = switchWidget->findChild<ToggleSwitch*>();
            if (toggle) {
                toggle->setChecked(false);
            }
        }

        // 重置复选框
        for (int col : {6, 7}) {
            QWidget* widget = ui->tableWidget_1->cellWidget(i, col);
            if (widget) {
                QCheckBox* cb = widget->findChild<QCheckBox*>();
                if (cb) {
                    cb->setChecked(false);
                }
            }
        }
    }
}

void DefectDlg::upPageTable3(const QList<GeneralParam> &generalParam)
{
    QMap<QString, int> paramRowMap = {
        {tr("General_minDist"), 0},
        {tr("General_fluorescence"), 1},
        {tr("General_NMS"), 2},
        {tr("General_shortAngle"), 3},
        {tr("General_shortEdge"), 4},
        {tr("General_missingAngle"), 5},
        {tr("General_minWoodLen"), 6},
        {tr("General_maxWoodLen"), 7},
        {tr("General_maxWaste"), 8},
        {tr("General_optWoodLen"), 9},
        {tr("General_truncation"), 10},
        {tr("General_removeTailing"), 11},
        {tr("General_sawThickness"), 12},
        {tr("General_defectMode"), 13},
        {tr("General_maxDowngrade"), 14},
        {tr("General_walnut"), 15}
    };
    for (const GeneralParam &param : generalParam) {
        if (paramRowMap.contains(param.paramName)) {
            int row = paramRowMap[param.paramName];
            if (row == 1 || row == 3 || row == 15) {
                QWidget* widget = ui->tableWidget_3->cellWidget(row, 1);
                if (widget) {
                    QLayout* layout = widget->layout();
                    if (layout && layout->count() > 0) {
                        ToggleSwitch* toggle = qobject_cast<ToggleSwitch*>(layout->itemAt(0)->widget());
                        if (toggle) {
                            bool isChecked = (param.paramValue == "1");
                            toggle->setChecked(isChecked);
                        }
                    }
                }
            } else {
                QTableWidgetItem* item = ui->tableWidget_3->item(row, 1);
                if (item) {
                    item->setText(param.paramValue);
                }
            }
        }
    }
}

void DefectDlg::upPageTable4(const QList<QualityGrade> &qualityGrade)
{
    for(int i=0;i<qualityGrade.size();i++){
        QTableWidgetItem* item = ui->tableWidget_4->item(i, 1);
        if (!item) {
            item = new QTableWidgetItem();
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget_4->setItem(i, 1, item);
        }
        item->setText(QString::number(qualityGrade[i].weight));
    }
}

void DefectDlg::upPageTable5(const QList<EdgeParam> &edgeParam)
{
    for(int i=0;i<edgeParam.size();i++){
        QTableWidgetItem* item = ui->tableWidget_5->item(i, 1);
        if (!item) {
            item = new QTableWidgetItem();
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget_5->setItem(i, 1, item);
        }
        item->setText(edgeParam[i].paramValue);
    }
}

void DefectDlg::upPageTable6(const QList<FixedLength> &fixedLength)
{
    for(int i=0;i<fixedLength.size();i++){
        QWidget* widget = ui->tableWidget_6->cellWidget(i, 1);
        if(widget) {
            QLayout* layout = widget->layout();
            if(layout && layout->count() > 0) {
                if(ToggleSwitch* toggle = qobject_cast<ToggleSwitch*>(layout->itemAt(0)->widget())) {
                    toggle->setChecked(fixedLength[i].isActive);
                }
            }
        }
        QTableWidgetItem* item = ui->tableWidget_6->item(i, 2);
        if (!item) {
            item = new QTableWidgetItem();
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget_6->setItem(i, 1, item);
        }
        item->setText(QString::number(fixedLength[i].length, 'f', 2));
    }
}

void DefectDlg::setWidgetsEnabled(QWidget *parent, bool enabled)
{
    for (auto *child : parent->findChildren<QWidget *>()) {

        if (auto *lineEdit = qobject_cast<QLineEdit *>(child)) {
            lineEdit->setEnabled(enabled);
        }else if (auto *comboBox = qobject_cast<QComboBox *>(child)) {
            comboBox->setEnabled(!enabled);
        }
        else if (auto *toggle = qobject_cast<ToggleSwitch *>(child)) {
            toggle->setAttribute(Qt::WA_TransparentForMouseEvents, !enabled); // 关键：禁用鼠标事件
        }
        else if (auto *tablewidget = qobject_cast<QTableWidget *>(child)) {
            if(enabled){
                tablewidget->setEditTriggers(QAbstractItemView::AllEditTriggers);
            }else{
                tablewidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
            }
        }
        else if (auto *checkBox = qobject_cast<QCheckBox *>(child)) {
            checkBox->setEnabled(enabled);
        }
    }
}

void DefectDlg::updateDefectScheme(const int &scheme_id)
{
    QString strDefect;
    strDefect = ui->Edit_defect->text();
    if(strDefect.isEmpty()){
        m_pMsg->Push(MESSAGE_TYPE_ERROR, tr("The defect name cannot be empty!"));
        return;
    }
    DefectScheme scheme;
    scheme.schemeName = strDefect;
    scheme.edgeSize = ui->lineEdit->text().toDouble();
    scheme.headEnd = ui->lineEdit_2->text().toDouble();
    scheme.isUnit = ui->radioButton->isCheckable()? false:true;
    if (!m_sql.updateDefectScheme(scheme_id,scheme)) {
        throw std::runtime_error("Failed to update defect settings");
    }
}

void DefectDlg::updateDefectSettings(const int& scheme_id)
{
    QList<DefectSetting> settings;
    int rowCount = ui->tableWidget_1->rowCount();
    for (int i = 0; i < rowCount; ++i) {
        DefectSetting setting;

        // 获取sort_order值（第10列）
        QTableWidgetItem* sortItem = ui->tableWidget_1->item(i, 10);
        if (sortItem) {
            setting.sortOrder = sortItem->text().toInt();
        } else {
            // 如果意外获取不到，使用行号+1作为默认值
            setting.sortOrder = i + 1;
        }

        // 获取缺陷名称（第0列）
        QTableWidgetItem* nameItem = ui->tableWidget_1->item(i, 0);
        if (nameItem) setting.defectName = nameItem->text();

        // 获取激活状态（第1列）
        QWidget* switchWidget = ui->tableWidget_1->cellWidget(i, 1);
        if (switchWidget) {
            ToggleSwitch* toggle = switchWidget->findChild<ToggleSwitch*>();
            if (toggle) setting.isActive = toggle->isChecked();
        }

        // 获取数值参数
        auto getDoubleValue = [&](int col) {
            QTableWidgetItem* item = ui->tableWidget_1->item(i, col);
            return item ? item->text().toDouble() : 0.0;
        };
        setting.longEdge = getDoubleValue(2);
        setting.shortEdge = getDoubleValue(3);
        setting.compensation = getDoubleValue(4);
        setting.openTogether = (getDoubleValue(5) > 0); // 布尔值
        setting.edgeCorrection = getDoubleValue(8);
        setting.confidence = getDoubleValue(9);

        // 获取复选框状态
        auto getCheckState = [&](int col) {
            QWidget* widget = ui->tableWidget_1->cellWidget(i, col);
            if (widget) {
                QCheckBox* cb = widget->findChild<QCheckBox*>();
                return cb ? cb->isChecked() : false;
            }
            return false;
        };
        setting.areaAssist = getCheckState(6);
        setting.unacceptable = getCheckState(7);

        settings.append(setting);
    }

    std::sort(settings.begin(), settings.end(), [](const DefectSetting& a, const DefectSetting& b) {
        return a.sortOrder < b.sortOrder;
    });

    if (!m_sql.updateDefectSettings(scheme_id, settings)) {
        throw std::runtime_error("Failed to update defect settings");
    }
}

void DefectDlg::updateGeneralParams(const int& scheme_id)
{
    QList<GeneralParam> params;
    const int sortOrderColumn = 2; // sort_order列索引

    // 使用静态常量避免重复构造
    static const QMap<int, QString> paramMap = {
        {0, tr("General_minDist")},
        {1, tr("General_fluorescence")},
        {2, tr("General_NMS")},
        {3, tr("General_shortAngle")},
        {4, tr("General_shortEdge")},
        {5, tr("General_missingAngle")},
        {6, tr("General_minWoodLen")},
        {7, tr("General_maxWoodLen")},
        {8, tr("General_maxWaste")},
        {9, tr("General_optWoodLen")},
        {10, tr("General_truncation")},
        {11, tr("General_removeTailing")},
        {12, tr("General_sawThickness")},
        {13, tr("General_defectMode")},
        {14, tr("General_maxDowngrade")},
        {15, tr("General_walnut")}
    };

    // 需要特殊处理的开关类型参数
    static const QSet<int> switchParams = {1, 3, 15};

    for (int i = 0; i < ui->tableWidget_3->rowCount(); ++i) {
        if (!paramMap.contains(i)) continue;

        GeneralParam param;
        param.paramName = paramMap[i];

        // 获取sort_order值
        QTableWidgetItem* sortItem = ui->tableWidget_3->item(i, sortOrderColumn);
        param.sortOrder = sortItem ? sortItem->text().toInt() : (i + 1);

        // 处理参数值
        if (switchParams.contains(i)) {
            // 开关类型参数
            if (auto widget = ui->tableWidget_3->cellWidget(i, 1)) {
                if (auto layout = widget->layout()) {
                    if (layout->count() > 0) {
                        if (auto toggle = qobject_cast<ToggleSwitch*>(layout->itemAt(0)->widget())) {
                            param.paramValue = toggle->isChecked() ? "1" : "0";
                        }
                    }
                }
            }
        } else {
            // 文本类型参数
            if (auto item = ui->tableWidget_3->item(i, 1)) {
                param.paramValue = item->text();
            }
        }

        params.append(param);
    }

    // 按sort_order排序
    std::sort(params.begin(), params.end(), [](const GeneralParam& a, const GeneralParam& b) {
        return a.sortOrder < b.sortOrder;
    });

    if (!m_sql.updateGeneralParams(scheme_id, params)) {
        throw std::runtime_error("Failed to update general parameters");
    }
}

void DefectDlg::updateQualityGrades(const int &scheme_id)
{
    QList<QualityGrade> grades;
    const int sortOrderColumn = 2; // sort_order列索引

    for (int i = 0; i < ui->tableWidget_4->rowCount(); ++i) {
        QualityGrade grade;

        // 获取sort_order值
        QTableWidgetItem* sortItem = ui->tableWidget_4->item(i, sortOrderColumn);
        grade.sortOrder = sortItem ? sortItem->text().toInt() : (i + 1);

        // 获取质量等级名称
        if (QTableWidgetItem* nameItem = ui->tableWidget_4->item(i, 0)) {
            grade.grade = nameItem->text();
        }

        // 获取权重值
        if (QTableWidgetItem* valueItem = ui->tableWidget_4->item(i, 1)) {
            bool ok;
            double weight = valueItem->text().toDouble(&ok);
            if (ok) {
                grade.weight = weight;
            } else {
                // 转换失败时使用默认值0
                grade.weight = 0.0;
            }
        } else {
            // 无数据时使用默认值0
            grade.weight = 0.0;
        }

        grades.append(grade);
    }


    std::sort(grades.begin(), grades.end(), [](const QualityGrade& a, const QualityGrade& b) {
        return a.sortOrder < b.sortOrder;
    });

    if (!m_sql.updateQualityGrades(scheme_id, grades)) {
        throw std::runtime_error("Failed to update quality grades");
    }
}

void DefectDlg::updateEdgeParams(const int& scheme_id)
{
    QList<EdgeParam> params;
    const int sortOrderColumn = 2;

    for (int i = 0; i < ui->tableWidget_5->rowCount(); ++i) {
        EdgeParam param;

        if (QTableWidgetItem* sortItem = ui->tableWidget_5->item(i, sortOrderColumn)) {
            param.sortOrder = sortItem->text().toInt();
        } else {
            param.sortOrder = i + 1;
        }

        if (QTableWidgetItem* nameItem = ui->tableWidget_5->item(i, 0)) {
            param.paramName = nameItem->text();
        }

        if (QTableWidgetItem* valueItem = ui->tableWidget_5->item(i, 1)) {
            param.paramValue = valueItem->text();
        }

        params.append(param);
    }

    std::sort(params.begin(), params.end(), [](const EdgeParam& a, const EdgeParam& b) {
        return a.sortOrder < b.sortOrder;
    });

    if (!m_sql.updateEdgeParams(scheme_id, params)) {
        throw std::runtime_error("Failed to update edge parameters");
    }
}

void DefectDlg::updateFixedLengths(const int &scheme_id)
{
    QList<FixedLength> lengths;
    const int sortOrderColumn = 3;

    for (int i = 0; i < ui->tableWidget_6->rowCount(); ++i) {
        FixedLength length;

        if (QTableWidgetItem* sortItem = ui->tableWidget_6->item(i, sortOrderColumn)) {
            length.sortOrder = sortItem->text().toInt();
        } else {
            length.sortOrder = i + 1;
        }

        if (QTableWidgetItem* nameItem = ui->tableWidget_6->item(i, 0)) {
            length.fName = nameItem->text();
        }

        if (auto widget = ui->tableWidget_6->cellWidget(i, 1)) {
            if (auto layout = widget->layout()) {
                if (layout->count() > 0) {
                    if (auto toggle = qobject_cast<ToggleSwitch*>(layout->itemAt(0)->widget())) {
                        length.isActive = toggle->isChecked();
                    }
                }
            }
        }

        if (QTableWidgetItem* lengthItem = ui->tableWidget_6->item(i, 2)) {
            bool ok;
            double lenValue = lengthItem->text().toDouble(&ok);
            length.length = ok ? lenValue : 0.0;
        }

        lengths.append(length);
    }

    std::sort(lengths.begin(), lengths.end(), [](const FixedLength& a, const FixedLength& b) {
        return a.sortOrder < b.sortOrder;
    });

    if (!m_sql.updateFixedLengths(scheme_id, lengths)) {
        throw std::runtime_error("Failed to update fixed lengths");
    }
}


void DefectDlg::on_Bt_Save_clicked()
{
    QString strDefect;
    strDefect = ui->Edit_defect->text();
    if(strDefect.isEmpty()){
        m_pMsg->Push(MESSAGE_TYPE_ERROR, tr("The defect name cannot be empty!"));
        return;
    }
    DefectScheme scheme;
    scheme.schemeName = strDefect;
    scheme.edgeSize = ui->lineEdit->text().toDouble();
    scheme.headEnd = ui->lineEdit_2->text().toDouble();
    scheme.isUnit = ui->radioButton->isCheckable()? false:true;
    int scheme_id = m_sql.insertDefectScheme(scheme);
    if(scheme_id){
        updateDatabase(scheme_id);
    }
    emit sigFormInfo();
    this->close();
}

void DefectDlg::updateDatabase(const int& scheme_id)
{
    if (scheme_id == -1) {
        m_pMsg->Push(MESSAGE_TYPE_ERROR, tr("No defect scheme selected!"));
        return;
    }

    try {
        updateDefectSettings(scheme_id);
        updateGeneralParams(scheme_id);
        updateQualityGrades(scheme_id);
        updateEdgeParams(scheme_id);
        updateFixedLengths(scheme_id);

        // 刷新修改时间显示
        DefectScheme scheme;
        if (m_sql.queryDefectScheme(scheme_id, scheme)) {
            ui->label_chang->setText(scheme.changeTime);
        }

        m_pMsg->Push(MESSAGE_TYPE_SUCCESS, tr("Defect scheme updated successfully!"));
    } catch (const std::exception& e) {
        m_pMsg->Push(MESSAGE_TYPE_ERROR, tr("Database update failed: ") + e.what());
    }
}



void DefectDlg::on_Bt_Updata_clicked()
{
    updateDefectScheme(m_currentSchemeId);
    updateDatabase(m_currentSchemeId);
    emit sigFormInfo();
    this->close();
}


void DefectDlg::on_Bt_Quite_clicked()
{
    this->close();
}

